package com.ashleyleung.jetpack_b_station.lifecycle

import com.ashleyleung.jetpack_b_station.lifecycle.LifeState.*
import timber.log.Timber

/**
 * @author lxy
 * @name 管理所注册进来的接口，这个接口就ILifeCycle
 * 保存当前View的生命周期状态
 * @class describe
 * @date 2022-06-23
 * Copyright (c)  Guangzhou GCI Science & Technology Co., Ltd.All rights reserved
 */
class LifeCycleProvider {
    private var currentLifeState: LifeState = LifeState.DESTROY

    private val lifecycleListener = arrayListOf<AbsLifecycle>()

    fun addLifeListener(listener: AbsLifecycle) {
        if (!lifecycleListener.contains(listener))
            lifecycleListener.add(listener)
    }

    fun removeLifeListener(listener: AbsLifecycle) {
        lifecycleListener.remove(listener)
    }

    fun makeLifeState(state: LifeState) {
        currentLifeState = state

        lifecycleListener.forEach {
            it.onViewLifeStateChange(state)
            when (state) {
                CREATE -> {
                    dispatchCreateState()
                }
                START -> dispatchStartState()
                RESUME -> dispatchResumeState()
                PAUSE -> dispatchPauseState()
                STOP -> dispatchStopState()
                DESTROY -> dispatchDestroyState()
            }
        }


    }

    private fun dispatchCreateState() {
        lifecycleListener.forEach {
            Timber.e("dispatchCreateState")
            it.onCreateLc()
        }
    }

    private fun dispatchStartState() {

        lifecycleListener.forEach {
            Timber.e("dispatchStartState %s", it.toString())
            it.onStartLc()
        }
    }

    private fun dispatchResumeState() {

        lifecycleListener.forEach {
            Timber.e("dispatchResumeState")
            it.onResumeLc()
        }
    }

    private fun dispatchDestroyState() {

        lifecycleListener.forEach {
            Timber.e("dispatchDestroyState")
            it.onDestroyLc()
        }
        lifecycleListener.clear()
    }

    private fun dispatchPauseState() {

        lifecycleListener.forEach {
            Timber.e("dispatchPauseState")
            it.onPauseLc()
        }
    }

    private fun dispatchStopState() {

        lifecycleListener.forEach {

            Timber.e("dispatchStopState")
            it.onStopLc()
        }
    }

    fun isAtLeast(state: LifeState): Boolean {
        var str = "current state $currentLifeState === $state"
        Timber.e(str)
        var isAtLeast :Boolean = currentLifeState>state
        Timber.e("isAtLeast %b",isAtLeast)
        Timber.e("isAtLeast2 $isAtLeast")
        return isAtLeast
    }


}